class Backend::ArticlesController < Backend::ApplicationController

  def index
    @articles = Article.includes(:preview, :category).order('id DESC').page params[:page]
    @categories = Category.all
  end

  def new
    @article = Article.new
  end

  def create
    @article = current_user.articles.build article_params
    if @article.save
    else
    end
  end

  def edit
    @article = current_user.articles.find params[:id]
  end

  def update
    @article = current_user.articles.find params[:id]
    if @article.update article_params
    else
    end
  end

  def destroy
    @article = current_user.articles.find params[:id]
    @article.destroy
  end

  def set_category
    @article = current_user.articles.find params[:id]
    @article.update category_id: params[:category_id]
    @categories = Category.all
  end

  def toggle_publish
    @article = current_user.articles.find params[:id]
    published_at = if @article.published_at.blank?
                     Time.zone.now
                   else
                     nil
                   end
    @article.update published_at: published_at
    @categories = Category.all
  end

  def edit_profile
    @article = Article.find params[:id]
  end

  def update_profile
    @article = Article.find params[:id]
    @article.keep_slug = true
    @article.published_at = Time.zone.now if @article.published_at.blank? and params[:publish] == '1'
    @article.update profile_params
  end

  private
  def article_params
    params.require(:article).permit(:title, :content_field)
  end

  def profile_params
    params.require(:article).permit(:title, :published_at, :slug)
  end
end
